package com.mrjy.wechat.bo;

import com.mrjy.common.entity.UserInfo;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.wechat.conts.WxConsts;
import com.mrjy.wechat.process.AccessToken;
import com.mrjy.wechat.util.WeChatUtil;

import net.coobird.thumbnailator.Thumbnails;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
 * 从微信服务器下载文件 Bo类
 * @author csshui
 *
 */
@Service("WeChatFileUploadBo")
public class WeChatFileUploadBo implements IWeChatFileUploadBo{
	
	@Resource
	private IWeChatOAuthBo weChatOAuthBo;
	@Resource 
	private IUserInfoDao userInfoDao;
	/**
	 * 根据mediaId 和accessToken下载微信图片
	 */
	@Override
	public Map<String, Object> uploadPmgWXFile(Map<String, Object> paramsMap) {
		Map<String, Object> map = new HashMap<String, Object>();
		int userId = (int) paramsMap.get("userId");
		String mediaId = (String) paramsMap.get("mediaId");//文件id


        AccessToken at = WxConsts.getAccessToken();
        String accessToken = at.getAccessToken();
		String getWxFileUrl = WxConsts.getWeChatApiURL(WxConsts.GET_WX_FILE_URL, accessToken , mediaId); 
		
		try {
			URL url = new URL(getWxFileUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setRequestMethod(WxConsts.HTTP_GET);
			String header = conn.getHeaderField("Content-Type");
			if ("text/plain".equals(header)) {
				JSONObject jsonObj = WeChatUtil.httpRequest(getWxFileUrl, WxConsts.HTTP_GET,null);
				if(jsonObj.has("errcode")){
					if("42001".equals(jsonObj.getString("errcode"))){//accessToken 超时
						weChatOAuthBo.clearAccessToken();
						weChatOAuthBo.getAccessToken(WxConsts.APPID, WxConsts.APPSECRET);
						conn.disconnect();
						map = uploadPmgWXFile(paramsMap);
					}else if ("40007".equals(jsonObj.getString("errcode"))) {//{"errcode":40007,"errmsg":"invalid media_id hint: [uvmpba0172e607]"}
						map.put("err_code", 3);
						map.put("err_msg", "不合法的图片id");
					}
					
				}
			}else if ("application/json; encoding=utf-8".equals(header)) {
				JSONObject jsonObj = WeChatUtil.httpRequest(getWxFileUrl, WxConsts.HTTP_GET,null);
				if(jsonObj.has("errcode")){
					if("45009".equals(jsonObj.getString("errcode"))){//下载图片次数达到日上限
						map.put("err_code", 4);
						map.put("err_msg", "下载微信图片次数达到日上限");
					}
				}
			}else if("image/jpeg".equals(header)){
				// 根据内容类型获取扩展名
				//String fileExt = WeixinUtil.getFileEndWitsh(conn.getHeaderField("Content-Type"));
				// 将mediaId作为文件名
				String fileExt = "jpg";
				
				// 分割符号 \\
				char fileSepartor = File.separatorChar;
				
				String rootPath = WxConsts.File_ROOT_PATH;

                String save_path = null;

                if (paramsMap.get("save_path") == null) {
                    save_path = WxConsts.ICO_SAVE_PATH;
                } else {
                    save_path = paramsMap.get("save_path").toString();
                }


                String direcotry = rootPath + fileSepartor + save_path;

                String saveFileName = Long.toString(System.currentTimeMillis()) + "." + fileExt;
				
				// 建立一个上传文件的输出流
				if (new File(direcotry).exists() == false) {// 不存在，创建目录
					new File(direcotry).mkdirs();
				}
				//将文件写入服务器
				BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
				FileOutputStream fos = new FileOutputStream(new File(direcotry+fileSepartor+saveFileName));
				byte[] buf = new byte[8096];
				int size = 0;
				while ((size = bis.read(buf)) != -1)
				fos.write(buf, 0, size);
				fos.close();
				bis.close();
				conn.disconnect();
				
				
				File saveFile = new File(direcotry+fileSepartor+saveFileName);
				if(saveFile.exists()){
					//压缩图片
					//用sourceRegion()实现图片裁剪  
					//图片中心300*300的区域,Positions.CENTER表示中心，还有许多其他位置可选  
					/*Thumbnails.of(saveFile).sourceRegion(Positions.CENTER,500,500)  
					.size(500,500).toFile(saveFile); */
					//按照比例进行缩小和放大  
					Thumbnails.of(saveFile).scale(0.5f).toFile(saveFile);//按比例缩小
					
					UserInfo tempUser = new UserInfo();
					tempUser.setId(userId);
					UserInfo info = userInfoDao.selectByUserInfo(tempUser);
					if (null != info) {
                        if (paramsMap.get("save_path") == null) {
                            info.setPicName(saveFileName);
                        } else {
                        	if(((String) paramsMap.get("save_path")).indexOf("familypic")!=-1){
                        		info.setFamilyPic(saveFileName);
                        	}
                        }
						int count = userInfoDao.updateById(info);
						if (count > 0 ) {
							map.put("err_code", 0);
							map.put("err_msg", "上传成功");
                            map.put("picName", saveFileName);
                        }else {
							map.put("err_code", 202);
							map.put("err_msg", "用户表头像更新失败");
						}
					}else {
						map.put("err_code", 201);
						map.put("err_msg", "用户id无效");
					}
					
					
				}else{
					map.put("err_code", 1);
					map.put("err_msg", "上传失败");
				}
			}else {
				map.put("err_code", -1);
				map.put("err_msg", "上传异常");
			}
		} catch (Exception e) {
			map.put("err_code", -1);
			map.put("err_msg", "上传异常");
		}
		
		return map;
	}


    /**
     * 根据mediaId 和accessToken下载微信资源
     */
    @Override
    public Map<String, Object> uploadWXFile(Map<String, Object> paramsMap) {
        Map<String, Object> map = new HashMap<String, Object>();
        String mediaId = (String) paramsMap.get("mediaId");//文件id

        AccessToken at = WxConsts.getAccessToken();
        if(null == at){
            at = weChatOAuthBo.getAccessToken(WxConsts.APPID, WxConsts.APPSECRET);
        }
        String accessToken = at.getAccessToken();
        String getWxFileUrl = WxConsts.getWeChatApiURL(WxConsts.GET_WX_FILE_URL, accessToken , mediaId);

        try {
            URL url = new URL(getWxFileUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod(WxConsts.HTTP_GET);
            String header = conn.getHeaderField("Content-Type");
            if ("text/plain".equals(header)) {
                JSONObject jsonObj = WeChatUtil.httpRequest(getWxFileUrl, WxConsts.HTTP_GET,null);
                if(jsonObj.has("errcode")){
                    if("42001".equals(jsonObj.getString("errcode"))){//accessToken 超时
                        weChatOAuthBo.clearAccessToken();
                        weChatOAuthBo.getAccessToken(WxConsts.APPID, WxConsts.APPSECRET);
                        conn.disconnect();
                        map = uploadPmgWXFile(paramsMap);
                    }else if ("40007".equals(jsonObj.getString("errcode"))) {//{"errcode":40007,"errmsg":"invalid media_id hint: [uvmpba0172e607]"}
                        map.put("err_code", 3);
                        map.put("err_msg", "不合法的图片id");
                    }

                }
            }else if ("application/json; encoding=utf-8".equals(header)) {
                JSONObject jsonObj = WeChatUtil.httpRequest(getWxFileUrl, WxConsts.HTTP_GET,null);
                if(jsonObj.has("errcode")){
                    if("45009".equals(jsonObj.getString("errcode"))){//下载图片次数达到日上限
                        map.put("err_code", 4);
                        map.put("err_msg", "下载微信图片次数达到日上限");
                    }
                }
            }else if("image/jpeg".equals(header)){
                // 根据内容类型获取扩展名
                //String fileExt = WeixinUtil.getFileEndWitsh(conn.getHeaderField("Content-Type"));
                // 将mediaId作为文件名
                String fileExt = "jpg";

                // 分割符号 \\
                char fileSepartor = File.separatorChar;

                String rootPath = WxConsts.File_ROOT_PATH;

                String direcotry = rootPath+fileSepartor+WxConsts.ICO_SAVE_PATH;

                String saveFileName = Long.toString(System.currentTimeMillis()) + "." + fileExt;

                // 建立一个上传文件的输出流
                if (new File(direcotry).exists() == false) {// 不存在，创建目录
                    new File(direcotry).mkdirs();
                }
                //将文件写入服务器
                BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
                FileOutputStream fos = new FileOutputStream(new File(direcotry+fileSepartor+saveFileName));
                byte[] buf = new byte[8096];
                int size = 0;
                while ((size = bis.read(buf)) != -1)
                    fos.write(buf, 0, size);
                fos.close();
                bis.close();
                conn.disconnect();


                File saveFile = new File(direcotry+fileSepartor+saveFileName);
                if(saveFile.exists()){
                    //压缩图片
                    //用sourceRegion()实现图片裁剪
                    //图片中心300*300的区域,Positions.CENTER表示中心，还有许多其他位置可选
					/*Thumbnails.of(saveFile).sourceRegion(Positions.CENTER,500,500)
					.size(500,500).toFile(saveFile); */
                    //按照比例进行缩小和放大
                    Thumbnails.of(saveFile).scale(0.5f).toFile(saveFile);//按比例缩小

                    UserInfo tempUser = new UserInfo();
                    UserInfo info = userInfoDao.selectByUserInfo(tempUser);
                    if (null != info) {
                        info.setPicName(saveFileName);
                        int count = userInfoDao.updateById(info);
                        if (count > 0 ) {
                            map.put("err_code", 0);
                            map.put("err_msg", "上传成功");
                            map.put("picName", info.getPicName());
                        }else {
                            map.put("err_code", 202);
                            map.put("err_msg", "用户表头像更新失败");
                        }
                    }else {
                        map.put("err_code", 201);
                        map.put("err_msg", "用户id无效");
                    }


                }else{
                    map.put("err_code", 1);
                    map.put("err_msg", "上传失败");
                }
            }else if("audio/amr".equals(header)){
                // 根据内容类型获取扩展名
                //String fileExt = WeixinUtil.getFileEndWitsh(conn.getHeaderField("Content-Type"));
                // 将mediaId作为文件名
                String fileExt = "amr";

                // 分割符号 \\
                char fileSepartor = File.separatorChar;

                String rootPath = WxConsts.File_ROOT_PATH;

                String direcotry = rootPath+fileSepartor+WxConsts.RECORD_SAVE_PATH;

                String saveFileName = Long.toString(System.currentTimeMillis()) + "." + fileExt;

                // 建立一个上传文件的输出流
                if (new File(direcotry).exists() == false) {// 不存在，创建目录
                    new File(direcotry).mkdirs();
                }
                //将文件写入服务器
                BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
                FileOutputStream fos = new FileOutputStream(new File(direcotry+fileSepartor+saveFileName));
                byte[] buf = new byte[8096];
                int size = 0;
                while ((size = bis.read(buf)) != -1)
                    fos.write(buf, 0, size);
                fos.close();
                bis.close();
                conn.disconnect();

                File saveFile = new File(direcotry+fileSepartor+saveFileName);
                if(saveFile.exists()){
                    map.put("err_code", 0);
                    map.put("err_msg", "上传成功");
                    map.put("record_name", saveFile.getName());
                    map.put("file", saveFile);
                }else{
                    map.put("err_code", 1);
                    map.put("err_msg", "上传失败");
                }
            }else {
                map.put("err_code", -1);
                map.put("err_msg", "上传异常");
            }
        } catch (Exception e) {
            map.put("err_code", -1);
            map.put("err_msg", "上传异常");
            return map;
        }

        return map;
    }

}
